package org.xmlpersist.database;

import java.sql.*;
import java.util.Map;
import javax.sql.DataSource;
import org.xmlpersist.util.DBPropertiesLoader;

public class DBConnection {

	private String driverClassName = null;

	private String url = null;

	private String userName = null;

	private String dbName = null;

	private String password = null;

	private DataSource dataSource = null;

	private DBPropertiesLoader dbPropertiesLoader = null;

	private Map<String, String> dbMap = null;

	private static Connection connection = null;

	public DBConnection() {
		dbPropertiesLoader = new DBPropertiesLoader();
		dbMap = dbPropertiesLoader.getDBInfo();
		this.driverClassName = dbMap.get("driverClassName");
		this.url = dbMap.get("url");
		this.userName = dbMap.get("userName");
		this.dbName = dbMap.get("dbName");
		this.password = dbMap.get("password");
	}

	public DBConnection(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	public DBConnection(Connection connection) {
		this.connection = connection;
	}

	public Connection getConnectionInstance() {
		return doConnect();

	}

	public Connection doConnect() {

		if (connection != null)
			return connection;
		else if (dataSource != null) {
			try {
				return dataSource.getConnection();

			} catch (SQLException e) {
				e.printStackTrace();
			}

		} else {
			try {

				Class.forName(driverClassName).newInstance();
				connection = (Connection) DriverManager.getConnection(url + "/"
						+ dbName, userName, password);
				System.out
						.println("XMLPersist : Database Connection is established successfully!");

			} catch (InstantiationException e) {

				e.printStackTrace();
			} catch (IllegalAccessException e) {

				e.printStackTrace();
			} catch (ClassNotFoundException e) {

				e.printStackTrace();
			} catch (SQLException e) {

				e.printStackTrace();
			}

			return connection;
		}
		return null;
	}

}
